import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import Pages from 'vite-plugin-pages'
import Layouts from 'vite-plugin-vue-layouts'
import vuetify from 'vite-plugin-vuetify'
import fs from 'fs'
import path from 'path'

// 添加浏览器 API polyfill for SSR
if (typeof global !== 'undefined') {
  global.ResizeObserver = global.ResizeObserver || class ResizeObserver {
    constructor(callback) { this.callback = callback; }
    observe() {}
    unobserve() {}
    disconnect() {}
  };
  
  global.IntersectionObserver = global.IntersectionObserver || class IntersectionObserver {
    constructor(callback) { this.callback = callback; }
    observe() {}
    unobserve() {}
    disconnect() {}
  };
}

// 自定义插件：处理联系表单提交
function contactFormPlugin() {
  return {
    name: 'contact-form-plugin',
    configureServer(server) {
      server.middlewares.use('/api/contact', (req, res, next) => {
        if (req.method === 'POST') {
          let body = ''
          req.on('data', chunk => {
            body += chunk.toString()
          })
          req.on('end', () => {
            try {
              const formData = JSON.parse(body)
              
              // 验证数据
              if (!formData.name || !formData.email || !formData.message) {
                res.writeHead(400, { 'Content-Type': 'application/json' })
                res.end(JSON.stringify({ error: '所有字段都是必填的' }))
                return
              }
              
              // 格式化数据
              const timestamp = new Date().toLocaleString('zh-CN', {
                timeZone: 'Asia/Shanghai',
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
              })
              
              const content = `\n=== 联系表单提交 ===\n提交时间: ${timestamp}\n姓名: ${formData.name}\n邮箱: ${formData.email}\n留言: ${formData.message}\n========================\n`
              
              // 写入文件（追加模式）
              const filePath = path.join(process.cwd(), 'info.txt')
              fs.appendFileSync(filePath, content, 'utf8')
              
              res.writeHead(200, { 'Content-Type': 'application/json' })
              res.end(JSON.stringify({ success: true, message: '提交成功' }))
            } catch (error) {
              console.error('处理表单提交时出错:', error)
              res.writeHead(500, { 'Content-Type': 'application/json' })
              res.end(JSON.stringify({ error: '服务器内部错误' }))
            }
          })
        } else {
          next()
        }
      })
    }
  }
}

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    Pages({
      // 为每个页面添加meta信息
      extendRoute(route, parent) {
        const meta = {
          "/": {
            title: "埃克森特气体",
            description:
              "埃克森特气体有限公司专注于电子特种气体业务，提供前驱体、特种气体、电子气体等产品，服务半导体、显示面板、光伏等行业客户。专业品质，全球服务。",
            keywords:
              "电子特种气体,前驱体,特种气体,电子气体,半导体气体,埃克森特,化学气体供应商",
          },
          "/about": {
            title: "关于我们 - 埃克森特气体有限公司 | 专业电子特种气体供应商",
            description:
              "埃克森特气体有限公司是专业的电子特种气体供应商，专注于为半导体、显示面板、光伏等行业提供高品质的前驱体、特种气体和电子气体产品。",
            keywords:
              "埃克森特气体,公司简介,电子特种气体供应商,半导体材料,化学气体公司,前驱体供应商",
          },
          "/products": {
            title: "产品展示 - 前驱体 特种气体 电子气体 | 埃克森特气体",
            description:
              "埃克森特气体产品包括TEOS、TMA、HCDS等前驱体，氙气、氖气、氪气、氦气等特种气体，以及各类电子气体，广泛应用于半导体制造等领域。",
            keywords:
              "TEOS,TMA,HCDS,氙气,氖气,氪气,氦气,前驱体产品,特种气体产品,电子气体产品,半导体材料,化学试剂",
          },
          "/contact": {
            title: "联系我们 - 埃克森特气体有限公司 | 电子特种气体供应商",
            description:
              "联系埃克森特气体有限公司，获取专业的电子特种气体产品和服务。我们为半导体、显示面板、光伏等行业提供优质的化学气体解决方案。",
            keywords:
              "联系埃克森特,电子特种气体咨询,化学气体供应商联系方式,前驱体采购,特种气体采购",
          },
        };

        if (meta[route.path]) {
          route.meta = { ...route.meta, ...meta[route.path] };
        }

        return route;
      },
    }),
    Layouts(),
    vuetify({ theme: { cspNonce: "dQw4w9WgXcQ" } }),
    contactFormPlugin(),
  ],
  ssgOptions: {
    script: "async",
    formatting: "minify",
    format: "cjs",
    mock: true,
    // 修复：使用正确的路由包含配置
    include: ["/", "/about", "/products", "/contact"],
    onBeforePageRender: (route, indexHTML, appCtx) => {
      // 为每个页面注入特定的meta标签
      const meta = route.meta || {};
      let metaTags = "";

      if (meta.title) {
        metaTags += `<title>${meta.title}</title>\n`;
        metaTags += `<meta property="og:title" content="${meta.title}">\n`;
      }

      if (meta.description) {
        metaTags += `<meta name="description" content="${meta.description}">\n`;
        metaTags += `<meta property="og:description" content="${meta.description}">\n`;
      }

      if (meta.keywords) {
        metaTags += `<meta name="keywords" content="${meta.keywords}">\n`;
      }

      // 添加通用的SEO标签
      metaTags += `<meta property="og:type" content="website">\n`;
      metaTags += `<meta property="og:url" content="https://www.exxonte.com${route.path}">\n`;
      metaTags += `<meta property="og:site_name" content="埃克森特气体有限公司">\n`;
      metaTags += `<meta name="twitter:card" content="summary_large_image">\n`;
      metaTags += `<meta name="robots" content="index, follow">\n`;
      metaTags += `<link rel="canonical" href="https://www.exxonte.com${route.path}">\n`;

      return indexHTML.replace("<head>", `<head>\n${metaTags}`);
    },
  },
  optimizeDeps: {
    include: ["vue", "vue-router", "vuetify", "vue-i18n"],
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@import "@/styles/variables.scss";`,
      },
    },
  },
  base: "./",
  build: {
    rollupOptions: {
      output: {
        inlineDynamicImports: true,
        format: "esm",
        entryFileNames: "assets/[name]-[hash].js",
        chunkFileNames: "assets/[name]-[hash].js",
        assetFileNames: "assets/[name]-[hash][extname]",
      },
    },
  },
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "src"),
    },
  },
  ssr: {
    noExternal: ["vuetify"],
  },
});
